<template>
  <div :class="$style.send">
    <ContentWrap>
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="tos" label="收件邮箱">
          <TagInput v-model="formData.tos" validator="email" placeholder="请输入收件邮箱"></TagInput>
        </el-form-item>
        <el-form-item prop="ccs" label="抄送邮箱">
          <TagInput v-model="formData.ccs" validator="email" placeholder="请输入抄送邮箱"></TagInput>
        </el-form-item>
        <el-form-item prop="template" label="邮件模板">
          <el-select v-model="formData.template" placeholder="请选择邮件模板" remote :remote-method="postPage" clearable filterable @change="changeHandle">
            <el-option v-for="(tl,i) in templateList" :key="i" :label="tl.name" :value="tl.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="theme" label="主题">
          <el-input v-model="formData.theme" placeholder="请输入主题" clearable />
        </el-form-item>
        <el-form-item label="邮件内容" prop="contentHtml">
          <Tinymce ref="tinymce" v-model="formData.contentHtml" />
        </el-form-item>
        <el-form-item label="附件" prop="emailAnnexList">
          <DialogUpload
            :key="uploadKey"
            action="/"
            title="选取文件"
            text="选取文件"
            :click-down="false"
            :auto-upload="false"
            :destroy="false"
            multiple
            :on-change="onFileChange"
            :on-remove="onFileChange"
            confirm-button-text="添加附件"
          />
        </el-form-item>
        <el-form-item>
          <div class="button-container" style="padding-top:0;">
            <Button type="primary" @click="submitHandle">发送</Button>
          </div>
        </el-form-item>
      </el-form>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import DialogUpload from '@/components/Upload/DialogUpload'
import { postPage } from '@/api/smsOrEmailTemp'
import Tinymce from '@/components/Tinymce'
import { deepCopy, filtersRaw, pageRequsetBody } from '@/utils'
import { mapGetters } from 'vuex'
import { postEmailRecord } from '@/api/email'
import TagInput from '@/components/TagInput'
export default {
  name: 'SendEmail',
  components: {
    ContentWrap,
    DialogUpload,
    Tinymce,
    TagInput
  },
  data() {
    const validatorEmail = (r, v, c) => {
      if (v.length > 0) {
        c()
      } else {
        c(new Error('请输收件邮箱'))
      }
    }
    return {
      uploadKey: 'upload', // 重新加载组件
      formData: {
        tos: [], // 收件邮箱
        ccs: [], // 抄送邮箱
        template: '', // 邮件模板
        theme: '', // 邮件主题
        content: '', // 邮件内容
        contentHtml: '', // 邮件html
        emailAnnexList: [], // 附件
        type: 1 // 邮件类型：1发2收
      },
      formRules: {
        tos: [{ required: true, type: 'array', message: '请输入收件邮箱', trigger: 'change' },
          { required: true, validator: validatorEmail, trigger: 'change' }], // 收件邮箱
        // template: [{ required: true, message: '请选择邮件模板', trigger: 'change' }], // 邮件模板
        theme: [{ required: true, message: '请输入邮件主题', trigger: 'change' }], // 邮件主题
        contentHtml: [{ required: true, message: '请输入邮件内容', trigger: 'change' }], // 邮件内容
        emailAnnexList: [{ required: false, message: '请选择附件', trigger: 'change' }] // 附件
      },
      submitData: {}, // 处理好的可上传数据
      templateList: [] // 模板列表
    }
  },
  computed: {
    ...mapGetters(['groupList'])
  },
  created() {
    this.getEmailAddress()
    if (this.$route.query.email) {
      this.$set(this.formData, 'tos', this.$route.query.email.split(','))
    }
    this.postPage()
  },
  methods: {
    // 选择的文件发生变化
    onFileChange(file, fileList) {
      this.$set(this.formData, 'emailAnnexList', fileList)
      // this.$set(this.formData, 'emailAnnexList', fileList)
    },
    // 获取email模板
    postPage(v) {
      const data = {
        filtersRaw: [
          filtersRaw('type', 2, '='),
          filtersRaw('name', v, 'like'),
          filtersRaw('enabled', 1, '='),
          filtersRaw('group', this.groupList.map(e => e.groupNo).join(','), 'in')
        ]
      }
      postPage(pageRequsetBody(data)).then(res => {
        this.templateList = res.data.records
      })
    },
    // 选择email模板后，更新邮件输入框内容
    changeHandle(id) {
      let t = Object.create(null)
      for (let i = 0; this.templateList.length > i; i++) {
        if (this.templateList[i].id === id) {
          t = this.templateList[i]
          break
        }
      }
      this.$set(this.formData, 'contentHtml', t.content || '')
      this.$refs.tinymce.setContent(this.formData.contentHtml)
    },
    // 发送邮件
    submitHandle() {
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        const formData = new FormData()
        const key = 'files'
        // 附件
        for (const f of data.emailAnnexList) {
          formData.append(key, f.raw)
        }
        delete data.emailAnnexList
        // 富文本
        let div = document.createElement('div')
        div.innerHTML = data.contentHtml
        data.content = div.innerText
        div = null
        // 删除模板
        delete data.template
        data.isTiming = 0 // 邮件默认不定时发送
        // 处理tos和ccs
        // formData.append('json', JSON.stringify(data))
        for (const key of Object.keys(data)) {
          const v = data[key]
          if (v instanceof Array) {
            for (let i = 0; i < v.length; i++) {
              formData.append(`${key}[${i}].emailAddress`, v[i])
            }
          } else {
            formData.append(key, v)
          }
        }
        return postEmailRecord(formData).then(res => {
          // this.$closePage()
          this.resetField()
          this.$message.success('发送成功！')
        })
      })
    },
    // 检查是否有邮件参数
    getEmailAddress() {
      if (this.$route.query.emailAddresseeList) {
        this.$set(this.formData, 'emailAddress', this.$route.query.emailAddresseeList)
      }
    },
    // 重置
    resetField() {
      this.$refs.form.resetFields()
      this.uploadKey = 'upload' + new Date().getTime()
      this.$refs.tinymce.setContent('')
    }
  }
}
</script>
<style lang='scss' module>
.send{

}
</style>
